﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ImportDataSetToList.cs" company="Collaboris Ltd.">
//   Copyright (c) Collaboris Ltd. All rights Reserved.
// </copyright>
// <summary>
//   Imports the DataSet to List.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Collaboris.Saf.Actions.Wss.List
{
    using System;
    using System.Collections.Generic;

    using Entities;
    using Engine;

    using SharePoint.Wss.Attributes;
    using SharePoint.Wss.Lists;
    using Utils;
    using System.Data;
    using Microsoft.SharePoint;
    using System.Collections;

    [CollaborisClass(
        Title = "Import DataSet to List.",
        ReleaseStatus = ReleaseStatus.Development,
        DisableDocumentation = false,
        ContactAuthorEmail = "Support@Collaboris.co.uk",
        Summary = "Imports the given Dataset data into the list." ,
        UndoImplemented = true,
        ClassGuid = "{f6417479-14b8-4e99-b5e3-7b5d6ac0ee38}"
    )
    ]
    public class ImportDataSetToList : WSSActionBase<ImportDataSetToListInfo>
    {
        /// <summary>
        /// Does the action.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        protected override ProcessStatus DoAction(SafContext context, ImportDataSetToListInfo entity)
        {
            this.Trace.TraceMethodStart("DoAction");

            ProcessStatus rstate = this.ProcessDo(context, entity);            

            this.Trace.TraceMethodEnd("DoAction");
            return rstate;
        }

        /// <summary>
        /// Processes the do.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        private ProcessStatus ProcessDo(SafContext context, ImportDataSetToListInfo entity)
        {
            this.Trace.TraceMethodStart("ProcessDo");

            SPList parentList = null;            
            parentList = SPListHelper.GetList(this.TargetWeb, entity.ListName);

            if (parentList != null)
            {
                // get the default one...
                DataTable table = entity.Data.Tables[0];

                SPListItem currentListItem;
                foreach (DataRow row in table.Rows)
                {
                    currentListItem = parentList.Items.Add();
                    foreach (DictionaryEntry item in entity.RowDefinition)
                    {
                        foreach (SPField field in currentListItem.Fields)
                        {
                            if (field.Title.Equals(item.Key.ToString(), StringComparison.OrdinalIgnoreCase))
                            {
                                currentListItem[field.Id] = row[item.Value.ToString()];
                                break;
                            }
                        }                        
                    }
                    currentListItem.Update();
                }
            }
            else
            {
                this.Trace.TraceWarning("List : {0} not found in the Web: {1}", 
                                            entity.ListName, this.TargetWeb.Url);
            }

            this.Trace.TraceMethodEnd("ProcessDo");
            return ProcessStatus.Success;
        }

        /// <summary>
        /// Checks the Data entity used by the Action for Validity
        /// </summary>
        /// <param name="context">The <see cref="SafContext"/> passed in by the SAF Engine.</param>
        /// <param name="entity">The data entity to Validate.</param>
        /// <param name="errors">List of <see cref="ValidationError"/>s</param>
        /// <param name="mode"><see cref="ProcessMode"/>signalling wheter we are Doing, or Undoing the action.</param>
        /// <returns>false if invalid; otherwise true.</returns>
        protected override bool IsValid(SafContext context, ImportDataSetToListInfo entity, ref List<ValidationError> errors, ProcessMode mode)
        {
            int currentCount = errors.Count;

            // Validate each object now.
            ValidateStringForNull(entity.ListName, "entity.ListName", ref errors);
            ValidateObjectForNull(entity.RowDefinition, "entity.RowDefinition", ref errors);
            ValidateObjectForNull(entity.Data, "entity.Data", ref errors);

            // Have we added errors ?
            return errors.Count == currentCount;
        }
    }
}